package com.ruiysoft.controller.logistics;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruiysoft.controller.logistics.vo.ExpressInfo;
import com.ruiysoft.entity.logistics.APILogisticsMessage;
import com.ruiysoft.entity.logistics.LogisticsException;
import com.ruiysoft.entity.order.OrderLogistics;
import com.ruiysoft.mapper.order.OrderLogisticsMapper;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultCode;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.service.logistics.ILogisticsCallback;
import com.ruiysoft.service.logistics.ILogisticsManageService;
import com.ruiysoft.service.logistics.ILogisticsQueryService;
import com.ruiysoft.service.order.IOrderInnerService;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
public class LogisticsController implements  LogisticsApi{

    private Logger logger = LoggerFactory.getLogger(LogisticsController.class);

    @Autowired
    private ILogisticsQueryService iLogisticsQueryService;

    @Autowired
    private ILogisticsManageService iLogisticsManageService;

    @Autowired
    private IOrderInnerService orderInnerService;

    @Autowired
    private ILogisticsCallback logisticsCallback;

    @Autowired
    OrderLogisticsMapper orderLogisticsMapper;

    @Override
    public Result<List<ExpressInfo.ExpressCompany>> expresscom(){

        List<ExpressInfo.ExpressCompany> companies = iLogisticsManageService.queryAllLogisticsCompany()
                .stream()
                .map(c->new ExpressInfo.ExpressCompany(c.getUnionCode(),c.getUnionName()))
                .collect(Collectors.toList());

        return ResultGenerator.genSuccessResult(companies);
    }

    @Override
    public Map<String,Object> logisticsCallBack(@PathVariable("apiSupplier") String apiSupplier,
                                                @PathVariable("shopID") Long shopID,
                                                @RequestParam(value="param") String param) {
        logger.error("LogisticsC allBack,APISupplier is {}",apiSupplier);
        logger.error("LogisticsC allBack,shopID is {}",shopID);
        logger.error("LogisticsC allBack,Param is {}",param);

        logisticsCallback.push2MQ(apiSupplier,shopID,param);

        Map<String,Object> re = new HashMap<>();
        re.put("result",Boolean.TRUE);
        re.put("returnCode","200");
        re.put("message","成功");
        return re;
    }

    @Override
    public Result<APILogisticsMessage> getExpressMessage(String expressNO,String expressCom) {
        Result<APILogisticsMessage> result = null;
        try {
            Long shopID = LoginContextUtil.instance().getEntryMicroShop().getId();
            APILogisticsMessage message = null;
            if(StringUtils.isEmpty(expressCom)){
                message = iLogisticsQueryService.queryLogisticsMessage(shopID, expressNO);
            }else{
                message = iLogisticsQueryService.queryLogisticsMessage(shopID, expressNO,expressCom);
            }
            result = new Result<>();
            result.setBizCode(ResultCode.CODE_SUCCESS);
            result.setData(message);
        }catch (LogisticsException e){
            result = new Result<>();
            result.setBizCode(ResultCode.CODE_COMMON_ERROR);
            result.setBizMessage("查询不到快递信息");
        }
        return result;
    }

    @Override
    public Result<ExpressInfo> getExpressInfo(String expressNO) {
        try {
            Long shopID = LoginContextUtil.instance().getEntryMicroShop().getId();
            return ResultGenerator.genSuccessResult(iLogisticsQueryService.revertExpressComByENO(shopID, expressNO));
        }catch (LogisticsException e){
            logger.error("无法获取物流公司信息",e);
            Result<ExpressInfo> result = new Result<>();
            result.setBizCode(ResultCode.CODE_COMMON_ERROR);
            result.setBizMessage("非法快递单号，请检查");
            return result;
        }
    }


    @Override
    public Result<Boolean> validate(String expressNO,String expressCom) {
        try {
            Long shopID = LoginContextUtil.instance().getEntryMicroShop().getId();
            return ResultGenerator.genSuccessResult(iLogisticsQueryService.validate(shopID, expressNO, expressCom));
        }catch (LogisticsException e){
            logger.error("物流查询异常",e);
            Result<Boolean> result = new Result<>();
            result.setBizCode(ResultCode.CODE_COMMON_ERROR);
            result.setBizMessage("快递单号与快递公司不匹配,请检查。");
            return result;
        }
    }


    @Override
    public Result<Boolean> isChecked(String expressNO,String expressCom) {
        try {
            Long shopID = LoginContextUtil.instance().getEntryMicroShop().getId();
            return ResultGenerator.genSuccessResult(iLogisticsQueryService.isExpressChecked(shopID,expressNO,expressCom));
        }catch (LogisticsException e){
            logger.error("物流查询异常",e);
            Result<Boolean> result = new Result<>();
            result.setBizCode(ResultCode.CODE_COMMON_ERROR);
            result.setBizMessage("暂时无法查询快递单号，请稍后。");
            return result;
        }
    }

    @Override
    public Result<Boolean> modify(Integer id, String enterpriseName, String enterpriseCode, String logisticsNo) {
        Result<Boolean> result = new Result<>();
        result.setBizCode(ResultCode.CODE_COMMON_ERROR);
        result.setBizMessage("操作失败");

        OrderLogistics orderLogistics = orderLogisticsMapper.selectById(id);
        if(orderLogistics != null) {
            orderLogistics.setUpdateTime(new Date());
            orderLogistics.setLogisticsEnterpriseName(enterpriseName);
            orderLogistics.setLogisticsEnterpriseCode(enterpriseCode);
            orderLogistics.setLogisticsNo(logisticsNo);

            if(orderLogisticsMapper.updateById(orderLogistics) > 0) {
                result.setBizCode(ResultCode.CODE_SUCCESS);
                result.setBizMessage("操作成功");
            }
        }
        return result;
    }
}
